package com.sq.universe.magic.conf;

import com.sq.universe.base.constants.BaseConstants;
import com.sq.universe.base.dao.AuthorityDao;
import com.sq.universe.base.utils.AuthUtils;
import com.sq.universe.system.entity.UserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.model.ApiInfo;
import org.ssssssss.magicapi.model.JsonBean;
import org.ssssssss.magicapi.model.Options;
import org.ssssssss.script.MagicScriptContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Order(1)   //拦截器顺序
public class PermissionInterceptor  implements RequestInterceptor {

    @Override
    public Object preHandle(ApiInfo info, MagicScriptContext context, HttpServletRequest request, HttpServletResponse response) {
        // 当前用户为开发人员允许访问
        UserEntity userEntity = (UserEntity) SecurityUtils.getSubject().getSession().getAttribute(BaseConstants.CURRENT_USER);
        if(userEntity != null){
            return null;
        }
        userEntity = AuthUtils.getCurrentUser();
        if(userEntity == null){
            return new JsonBean<>(401,"请登录");
        }
        // 获取配置的接口选项属性
        String url = request.getServletPath().replace("/",":");
        url = "magic" + url;
        String menuName = AuthUtils.getCurrnetAuth().get(url);
        if(StringUtils.isBlank(menuName)){
            // 需要注意的是，拦截器返回的不会走ResultProvider。
            return new JsonBean<>(401,"无权访问");
        }
        // 放行
        return null;
    }
}
